package com.redis.demo.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author keven
 * @date 2025-05-10 8:24 上午
 * @Description
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 实现setNx
     */
    public boolean lockOfSetNx(String key,String value,Long millisecond){
        return (boolean) redisTemplate.execute((RedisCallback) connection -> {
            //获取锁
            Boolean acquire = connection.setNX(key.getBytes(), value.getBytes());
            if (acquire) {
                redisTemplate.expire(key, millisecond, TimeUnit.MILLISECONDS);
                return true;
            }
            return false;
        });
    }



}
